package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.PeriodInventoryMapper;
import com.ruoyi.system.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.InventoryCheckMapper;
import com.ruoyi.system.service.IInventoryCheckService;
import org.springframework.util.CollectionUtils;

/**
 * 盘点单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-13
 */
@Service
public class InventoryCheckServiceImpl implements IInventoryCheckService 
{
    @Autowired
    private InventoryCheckMapper inventoryCheckMapper;

    /**
     * 查询盘点单
     * 
     * @param id 盘点单主键
     * @return 盘点单
     */
    @Override
    public InventoryCheck selectInventoryCheckById(Long id)
    {
        return inventoryCheckMapper.selectInventoryCheckById(id);
    }

    /**
     * 查询盘点单列表
     * 
     * @param inventoryCheck 盘点单
     * @return 盘点单
     */
    @Override
    public List<InventoryCheck> selectInventoryCheckList(InventoryCheck inventoryCheck)
    {
        return inventoryCheckMapper.selectInventoryCheckList(inventoryCheck);
    }

    /**
     * 新增盘点单
     * 
     * @param inventoryCheck 盘点单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertInventoryCheck(InventoryCheck inventoryCheck)
    {
        String userName = SecurityContextHolder.getUserName();
        inventoryCheck.setCreateOrderUser(userName);
        inventoryCheck.setStatus("1");
        inventoryCheck.setCreateTime(DateUtils.getNowDate());
        int rows = inventoryCheckMapper.insertInventoryCheck(inventoryCheck);
        insertInventoryCheckInfo(inventoryCheck);

        //保存期初期末数据
        List<InventoryCheckInfo> inventoryCheckInfoList = inventoryCheck.getInventoryCheckInfoList();
        savePeriodInventory(inventoryCheckInfoList);//保存期初期末数据

        return rows;
    }

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private PeriodInventoryMapper periodInventoryMapper;

    private void savePeriodInventory(List<InventoryCheckInfo> inventoryCheckInfoList) {
        //        期初期末表：
        //        日期、产品编号、产品名称、产品规格、类别、存储单位、仓库、期初、入库、出库、期末
        List<PeriodInventory> periodInventoryList = new ArrayList<>();
        for (InventoryCheckInfo inventoryCheckInfo : inventoryCheckInfoList) {
            PeriodInventory periodInventory = new PeriodInventory();
            periodInventory.setCreateTime(new Date());
            periodInventory.setName(inventoryCheckInfo.getProductName());
            periodInventory.setCode(inventoryCheckInfo.getProductCode());
            periodInventory.setSpec(inventoryCheckInfo.getProductSpec());
            //根据产品名称查询类别
            ProductType productType =  productMapper.selectProductTypeByName(inventoryCheckInfo.getProductName());
            String category = productType.getName();
            periodInventory.setCategory(category);
            Unit unit = productMapper.selectUnitByProductName(inventoryCheckInfo.getProductName());
            periodInventory.setUnit(unit.getName());
            Warehouse warehouse = productMapper.selectWarehouseByProductName(inventoryCheckInfo.getProductName());
            periodInventory.setWarehouse(warehouse.getName());
//            期初:上一时期的期末值
            // 获取当前日期减一天的日期
            LocalDate previousDate = LocalDate.now().minusDays(1);
            Date previousDateAsDate = Date.from(previousDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            PeriodInventory params = new PeriodInventory();
            params.setCreateTime(previousDateAsDate);
            List<PeriodInventory> periodInventories = periodInventoryMapper.selectPeriodInventoryList(params);
            if (!CollectionUtils.isEmpty(periodInventories)){
                periodInventory.setInitialStock(periodInventories.get(0).getFinalStock());
            }else{
                periodInventory.setInitialStock(BigDecimal.ZERO);
            }
//            入库、
            BigDecimal incomingStock = periodInventoryMapper.selectIncomingStock(inventoryCheckInfo.getProductName(), LocalDate.now().toString());
            periodInventory.setIncomingStock(incomingStock);
            // 出库
            BigDecimal outgoingStock = periodInventoryMapper.selectOutgoingStock(inventoryCheckInfo.getProductName(), LocalDate.now().toString());
            periodInventory.setOutgoingStock(outgoingStock);

            // 期末
            BigDecimal finalStock = periodInventory.getInitialStock()
                    .add(periodInventory.getIncomingStock())
                    .subtract(periodInventory.getOutgoingStock());
            periodInventory.setFinalStock(finalStock);


            periodInventoryList.add(periodInventory);
        }

        if (!CollectionUtils.isEmpty(periodInventoryList)) {
            // 批量保存期初期末数据
            periodInventoryMapper.batchInsertPeriodInventory(periodInventoryList);
        }

    }

    /**
     * 修改盘点单
     * 
     * @param inventoryCheck 盘点单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateInventoryCheck(InventoryCheck inventoryCheck)
    {
        inventoryCheckMapper.deleteInventoryCheckInfoByInventoryCheckId(inventoryCheck.getId());
        insertInventoryCheckInfo(inventoryCheck);
        return inventoryCheckMapper.updateInventoryCheck(inventoryCheck);
    }

    /**
     * 批量删除盘点单
     * 
     * @param ids 需要删除的盘点单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteInventoryCheckByIds(Long[] ids)
    {
        inventoryCheckMapper.deleteInventoryCheckInfoByInventoryCheckIds(ids);
        return inventoryCheckMapper.deleteInventoryCheckByIds(ids);
    }

    /**
     * 删除盘点单信息
     * 
     * @param id 盘点单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteInventoryCheckById(Long id)
    {
        inventoryCheckMapper.deleteInventoryCheckInfoByInventoryCheckId(id);
        return inventoryCheckMapper.deleteInventoryCheckById(id);
    }

    /**
     * 新增盘点明细信息
     * 
     * @param inventoryCheck 盘点单对象
     */
    public void insertInventoryCheckInfo(InventoryCheck inventoryCheck)
    {
        List<InventoryCheckInfo> inventoryCheckInfoList = inventoryCheck.getInventoryCheckInfoList();
        Long id = inventoryCheck.getId();
        if (StringUtils.isNotNull(inventoryCheckInfoList))
        {
            List<InventoryCheckInfo> list = new ArrayList<InventoryCheckInfo>();
            for (InventoryCheckInfo inventoryCheckInfo : inventoryCheckInfoList)
            {
                inventoryCheckInfo.setInventoryCheckId(id);
                list.add(inventoryCheckInfo);
            }
            if (list.size() > 0)
            {
                inventoryCheckMapper.batchInventoryCheckInfo(list);
            }
        }
    }
}
